package com.example.studentmanager.Controller;

import com.example.studentmanager.Pojo.Student;
import com.example.studentmanager.Service.impl.Studentimpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "instu",value = "/instu")
public class Instudent extends HttpServlet {
    private  String error="插入失败  请重新尝试";
    private  String  error1="账号已经存在无法插入";
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        res.setCharacterEncoding("utf-8");
        String key=req.getParameter("studentid");
        if (key!=null) {
            Studentimpl stuservice = new Studentimpl();
            List<Student> list1 = new ArrayList<>();
            list1 = stuservice.queryByKey(key);
           if (list1.isEmpty()){
               Student s=new Student();
               s.setStudentid(Integer.parseInt(req.getParameter("studentid")));
               s.setName(req.getParameter("name"));
               s.setCls(req.getParameter("cls"));
               s.setPhone(Integer.parseInt(req.getParameter("phone")));
               s.setGrade(req.getParameter("grade"));
               s.setHome(req.getParameter("home"));
               s.setState(req.getParameter("state"));
               Studentimpl ss=new Studentimpl();
               int r=  ss.InsertIntoStudent(s);
               if (r>0){
                   HttpSession session = req.getSession();
                   String admin="admin";
                   String password="123456";
                   session.setAttribute("user",admin);
                   session.setAttribute("password",password);

                   req.getRequestDispatcher("main").forward(req,res);
               }else {
                   req.setAttribute("error",error);
                   RequestDispatcher ds= req.getRequestDispatcher("./404.jsp");
                   ds.forward(req,res);
               }

           }else {
               System.out.println("  账号已经存在");
               RequestDispatcher ds= req.getRequestDispatcher("./404.jsp");
               req.setAttribute("error",error1);
               ds.forward(req,res);
           }
        }else {
            System.out.println("学号有错误");
            RequestDispatcher ds= req.getRequestDispatcher("./404.jsp");
            req.setAttribute("error",error);
            ds.forward(req,res);
        }

    }
}
